import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/components/my_alert.dart';
import 'package:hxdj/common/components/my_app_bottom.dart';
import 'package:hxdj/common/components/my_clip_rect.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/components/my_webview.dart';
import 'package:hxdj/common/my_common.dart';
import 'package:hxdj/common/my_global.dart';
import 'package:hxdj/common/my_header_global.dart';
// import 'package:hxdj/common/my_upgrade_checker.dart';
import 'package:hxdj/common/routers/navigator.dart';
import 'package:hxdj/common/utils/my_permission.dart';
import 'package:hxdj/home/recommend_technician/recommend_technician_page.dart';
import 'package:hxdj/home/select_technician/select_technician_page.dart';
import 'package:hxdj/home/technician_detail.dart/technician_detail_page.dart';
import 'package:hxdj/login/login_page.dart';
import 'package:hxdj/login/user_model.dart';
import 'package:hxdj/mine/about_mine_page.dart';
import 'package:hxdj/mine/cancel_account/cancel_account_page.dart';
import 'package:hxdj/mine/member_center/member_center_page.dart';
import 'package:hxdj/mine/questions/questions_page.dart';
import 'package:hxdj/mine/safe_account/safe_account_page.dart';
import 'package:hxdj/recommend_project/recommend_project_page.dart';
import 'package:hxdj/tupeng/tupeng_text.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:provider/provider.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key});

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  Map<String, String> pageMap = {
    "登录页面": LoginPage.routeName,
    "关于我的页面": AboutMinePage.routeName,
    "注销账号页面": CancelAccountPage.routeName,
    "常见问题": QuestionsPage.routeName,
    "账号安全页面": SafeAccountPage.routeName,
    '网页页面': MyWebviewPage.routeName,
    "会员中心": MemberCenterPage.routeName,
    '选择技师': SelectTechnicianPage.routeName,
    '推荐技师': RecommendTechnicianPage.routeName,
    '推荐项目': RecommendProjectPage.routeName,
    '技师详情': TechnicianDetailPage.routeName,
    'tupeng_text': TupengPage.routeName,
  };

  @override
  void deactivate() {
    super.deactivate();

    var bool = ModalRoute.of(context)!.isCurrent;
    if (bool) {
      // 监听到页面返回，发请求刷新页面操作
      print('返回N我的页面');
    }
  }

  //头像个人信息
  Widget _buildHeader() {
    double topPadding = MediaQuery.of(context).padding.top;
    return Consumer(builder: (context, MyGlobalViewModel globalViewModel, child) {
      //获取用户信息
      UserModel? userModel = globalViewModel.userModel;

      UserDetailModel? userDetailModel = globalViewModel.userDetailModel;

      return Stack(children: [
        Column(
          children: [
            Container(
              color: Colors.white,
              padding: EdgeInsets.only(top: topPadding + 20, bottom: 28, left: 15),
              child: Row(
                children: [
                  //头像
                  MyClipRect(
                    imageUrl: userModel?.picUrl ?? "",
                    width: 80.w,
                    radius: 40.w,
                  ),

                  //名字 & 手机号
                  Container(
                    padding: EdgeInsets.only(left: 15.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          padding: EdgeInsets.only(bottom: 10.h),
                          child: Row(
                            children: [
                              Text(userModel?.nickName ?? "",
                                  style: TextStyle(fontSize: 15.sp, color: Colors.black, fontWeight: FontWeight.bold)),
                              userModel?.isVip == 1
                                  ? Padding(
                                      padding: EdgeInsets.only(left: 5.w),
                                      child: const MyImage(imageName: "ic_vip_mine", width: 37.5, height: 15),
                                    )
                                  : Container(),
                            ],
                          ),
                        ),
                        Text(CommonPlugin.formatMobile(userModel!.mobile ?? ""),
                            style: TextStyle(fontSize: 14.sp, color: Colors.black)),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              height: 62,
              color: MyColours.bgColor,
            ),
          ],
        ),

        //Vip标识3
        Positioned(
          left: 13,
          right: 13,
          bottom: 25,
          child: MyTapWidget(
            onTap: () {
              //跳转会员中心
              NavigatorUtils.push(context, MemberCenterPage.routeName).then((value) {
                //刷新下用户信息
                debugPrint("刷新下用户信息");
              });
            },
            child: Container(
              height: 50,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0.w), topRight: Radius.circular(8.0.w)),
                gradient: const LinearGradient(
                  colors: [
                    Color.fromRGBO(29, 29, 28, 1),
                    Color.fromRGBO(60, 54, 54, 1),
                  ],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                ),
              ),
              child: Row(
                children: [
                  //vip 图

                  Container(
                      padding: EdgeInsets.only(left: 10.w),
                      child: const MyImage(imageName: "ic_home_vip", width: 40, height: 15)),

                  Padding(
                    padding: EdgeInsets.only(left: 20.w), //您好，尊贵的月卡会员！
                    child: MyText(userDetailModel?.userData?.isVip == 1 ? "您好，尊贵的月卡会员！" : "加入会员享优惠特权",
                        color: MyColours.colorF0D3BB, fontSize: 16.sp),
                  ),

                  const Spacer(),
                  //一个渐变的按钮
                  Container(
                    margin: EdgeInsets.only(right: 10.w),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20.w),
                      gradient: const LinearGradient(
                        colors: [
                          Color.fromRGBO(247, 222, 198, 1),
                          Color.fromRGBO(230, 189, 152, 1),
                        ],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                      ),
                    ),
                    padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.w),
                    child: MyText(userDetailModel?.userData?.isVip == 1 ? "立即续费" : "立即加入",
                        color: MyColours.text, fontSize: 12.sp, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
            ),
          ),
        )
      ]);
    });
  }

  //常用功能
  Widget _buildCommon() {
    List<String> titles = ["常见问题", "账号安全", "联系客服", "关于我们"];
    List<String> imageNames = ["ic_qa", "ic_safe_account", "ic_contact_service", "ic_about_us"];
    List<String> routeNames = [QuestionsPage.routeName, SafeAccountPage.routeName, "联系客服", AboutMinePage.routeName];

    return Column(
        children: titles.map((e) {
      int index = titles.indexOf(e);
      return GestureDetector(
        onTap: () {
          if (e == "联系客服") {
            MyAlertManager.showAlert(AlertType.customWidget, context, "", "", child: _buildServiceQrCode());
            return;
          }
          NavigatorUtils.push(context, routeNames[index]).then((value) => debugPrint("我的二级页面的回调object"));
        },
        child: Container(
          color: Colors.white,
          child: Row(children: [
            Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                child: MyImage(imageName: imageNames[index], width: 30)),
            Expanded(
                child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 19),
                    decoration: BoxDecoration(
                        border: Border(
                      bottom: BorderSide(color: MyColours.colorE1E1E1, width: index == titles.length - 1 ? 0 : 1),
                    )),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(titles[index], style: const TextStyle(fontSize: 15, color: Colors.black)),
                        Container(
                            padding: const EdgeInsets.only(right: 10),
                            child: const MyImage(imageName: "ic_arrow_right", width: 15))
                      ],
                    )))
          ]),
        ),
      );
    }).toList());
  }

  //客服二维码
  _buildServiceQrCode() {
    GlobalKey globalKey = GlobalKey();

    MyGlobalViewModel globalViewModel = MyGlobalViewModel.getGlobalViewModel(context);
    StandardDetailModel? standardDetailModel = globalViewModel.standardDetailModel;

    return Container(
        decoration: BoxDecoration(
            color: MyColours.materialBg,
            //设置四周圆角 角度
            borderRadius: BorderRadius.circular(30.w)),
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Padding(
            padding: EdgeInsets.only(top: 40.w, bottom: 20.w),
            child: MyText("安心下单 售后无忧 守护您的权益 ", textStyle: MyTextStyles.textBlackBold14),
          ),
          RepaintBoundary(
            key: globalKey,
            child: Container(
                decoration: BoxDecoration(
                    color: MyColours.bgColor,

                    //设置四周圆角 角度
                    borderRadius: BorderRadius.circular(10.w)),
                  child: MyCachedNetworkImage(imageUrl: standardDetailModel?.kefuQrcode ?? "", width: 140.w))

              //  QrImageView(data: , size: 140.w)),
          ),
          Padding(
            padding: EdgeInsets.only(top: 15.w, bottom: 40.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MyTapWidget(
                  onTap: () {
                    //拨打电话
                    CommonPlugin.callNumber(standardDetailModel?.kefuMobile ?? "");
                  },
                  child: Column(
                    children: [
                      MyImage(imageName: "ic_service", width: 42.w),
                      Padding(
                        padding: EdgeInsets.only(top: 10.w),
                        child: const MyText("联系人工客服", color: MyColours.color4F4B46, fontSize: 14),
                      ),
                    ],
                  ),
                ),
                SizedBox(width: 50.w),
                MyTapWidget(
                  onTap: () {
                    saveScreenshot(globalKey);
                  },
                  child: Column(
                    children: [
                      MyImage(imageName: "ic_save_photo", width: 42.w),
                      Padding(
                        padding: EdgeInsets.only(top: 10.w),
                        child: const MyText("保存到相册", color: MyColours.color4F4B46, fontSize: 14),
                      ),
                    ],
                  ),
                )
              ],
            ),
          )
        ]));
  }

  //保存图
  Future<Uint8List?> takeScreenshot(GlobalKey globalKey) async {
    try {
      RenderRepaintBoundary boundary = globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
      ui.Image image = (await boundary.toImage(pixelRatio: 3.0)); // 调整分辨率以适应高像素密度设备
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      if (byteData != null) {
        Uint8List pngBytes = byteData.buffer.asUint8List();
        return pngBytes;
      }
    } catch (e) {
      return null;
    }
    return null;
  }

  saveScreenshot(GlobalKey globalKey) async {
    Uint8List? screenshotBytes = await takeScreenshot(globalKey);
    if (screenshotBytes != null) {
      //获取保存图片的权限
      // ignore: use_build_context_synchronously
      bool permission = await MyPermission.requestPermission(context);
      if (permission) {
        final result = await ImageGallerySaver.saveImage(screenshotBytes);
        debugPrint('result= $result'); // 打印保存结果
        EasyLoading.showSuccess("已保存到本地");
        // ignore: use_build_context_synchronously
        Navigator.pop(context);
      }
    } else {
      EasyLoading.showError("保存失败");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: MyColours.bgColor,
        // floatingActionButton: FloatingActionButton(
        //   onPressed: () async {
        //     // MyAlertManager.showAlert(AlertType.iosMode, context, "您确定要取消订单吗？", "", onClose: () {});

        //     // //选择了那个支付方式, 传一个闭包过去
        //     // onSelectCallback(value) {
        //     //   print("object ${value}");
        //     // }
        //     // MyAlertManager.sheetAlert(AlertType.sheetSelectPayMode, context, "", "", onClose: () {}, object: {"price":"100","onSelectCallback":onSelectCallback});

        //     // MyAlertManager.sheetAlert(AlertType.sheetPayStatue, context, "支付完成", "ic_pay_success", onSure: (){

        //     // });

        //     //   MyAlertManager.sheetAlert(AlertType.sheetPayStatue, context, "支付失败", "ic_pay_fail", onSure: (){
              
        //     // });
        //     //检测用户是否升级
        //     // MyUpgradeChecker.checkForUpgrade(context);
        //   },
        //   tooltip: 'Show iOS Style Alert',
        //   child: const Icon(Icons.add),
        // ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              //头像个人信息
              _buildHeader(),

              //常见问题, 账号&安全 联系客服, 关于我们
              _buildCommon(),

              MyAppBottom.buildBottom(padding: EdgeInsets.only(top: 35.h, left: 40.h, right: 40.h)),

              // Wrap(
              //     runSpacing: 5.0,
              //     spacing: 5.0,
              //     children: pageMap.keys.map((e) {
              //       return MaterialButton(
              //         color: Colors.orange,
              //         textColor: Colors.white,
              //         child: Text(e, style: const TextStyle(color: Colors.yellow)),
              //         onPressed: () {
              //           NavigatorUtils.push(context, pageMap[e]!);
              //         },
              //       );
              //     }).toList()),
            ],
          ),
        ));
  }
}
